﻿using System;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Framework.Exceptions
{
    public static class ExceptionHandlingManager
    {
        private static ExceptionManager _exceptionManager;
        private static LogWriter _logWriter;


        public static void Configure()
        {
            var configuration = ConfigurationSourceFactory.Create();
            var factory = new ExceptionPolicyFactory(configuration);
            var logWriterFactory = new LogWriterFactory(configuration);

            _logWriter = logWriterFactory.Create();
            Logger.SetLogWriter(_logWriter);

            _exceptionManager = factory.CreateManager();
            ExceptionPolicy.SetExceptionManager(_exceptionManager);
        }


        #region Wrappers
        
        public static void Process(Action action, string policyName)
        {
            _exceptionManager.Process(action, policyName);
        }

        public static TResult Process<TResult>(Func<TResult> action, TResult defaultResult, string policyName)
        {
            return _exceptionManager.Process(action, defaultResult, policyName);
        }

        public static TResult Process<TResult>(Func<TResult> action,  string policyName)
        {
            return _exceptionManager.Process(action, policyName);
        }

        public static bool HandleException(Exception exception, string policyName)
        {
            return ExceptionPolicy.HandleException(exception, policyName);
        }
        
        public static bool HandleException(Exception exception, string policyName, out Exception exceptionToThrow)
        {
            return ExceptionPolicy.HandleException(exception, policyName, out exceptionToThrow);
        }

        #endregion
    }
}
